<template>
  <div class="content">
    <el-card class="card-box">
      <div class="card-box--headerwrap">
        <el-page-header content="详情页面" @back="goback"></el-page-header>
        <div class="card-box--setbtn" v-if="isEdit">
          <el-button @click="goback">取消</el-button>
          <el-button type="primary" @click="handleSubmit">保存</el-button>
        </div>
      </div>
    </el-card>
    <el-card class="card-box form-box">
      <div>
        <el-row class="form-info" v-if="route.query.mode !== 'add'">
          <el-col :span="7" :offset="1"
            >申请人: {{ infoState.createUserName }}</el-col
          >
          <el-col :span="7">创建时间: {{ infoState.createTime }}</el-col>
          <el-col :span="8">文档编号: {{ infoState.billNum }}</el-col>
        </el-row>
        <el-form
          ref="formRef"
          :model="formState"
          :rules="Rules"
          label-width="160px"
        >
          <el-form-item
            label="变更名称"
            placeholder="请输入变更名称"
            prop="alterationName"
          >
            <el-input
              :disabled="!isEdit"
              v-model="formState.alterationName"
              class="width-custom220"
            />
          </el-form-item>
          <el-form-item
            label="所属项目"
            placeholder="请选择所属项目"
            prop="projectName"
          >
            <el-select
              v-model="formState.projectName"
              placeholder="请选择"
              ref="projectRef"
              :disabled="!isEdit"
            >
              <el-option :value="projectList">
                <el-tree
                  class="tree-option"
                  :data="projectList"
                  accordion
                  node-key="id"
                  ref="projectTreeRef"
                  highlight-current
                  :props="defaultProps"
                  @check-change="handleCheckChange"
                  check-on-click-node
                  :expand-on-click-node="false"
                >
                </el-tree>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="合同名称"
            placeholder="请选择合同"
            prop="contractId"
          >
            <el-select
              v-model="formState.contractId"
              ref="contractRef"
              @change="handleChangeContract"
              :disabled="!isEdit"
            >
              <el-option
                class="default-option"
                v-for="item in contracList"
                :key="item.contractId"
                :label="item.contractName"
                :value="item.contractId"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="单体(子项)工程名称"
            placeholder="请输入单体(子项)工程名称"
            prop="subProjectName"
          >
            <el-input
              :disabled="!isEdit"
              v-model="formState.subProjectName"
              class="width-custom220"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="分部"
            placeholder="请输入分部名称"
            prop="segmentName"
          >
            <el-input
              :disabled="!isEdit"
              v-model="formState.segmentName"
              class="width-custom220"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="子分部"
            placeholder="请输入子分部名称"
            prop="subSegmentName"
          >
            <el-input
              :disabled="!isEdit"
              v-model="formState.subSegmentName"
              class="width-custom220"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="申请变更理由或原因"
            placeholder="请输入"
            prop="alterationReason"
          >
            <el-input
              :disabled="!isEdit"
              type="textarea"
              row="3"
              v-model="formState.alterationReason"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="建议方案"
            placeholder="请输入"
            prop="proposedScheme"
          >
            <el-input
              :disabled="!isEdit"
              type="textarea"
              row="3"
              v-model="formState.proposedScheme"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="影响造价估算(包括返工重做，加固补强)"
            placeholder="请输入"
            prop="impactFraudEstimation"
          >
            <el-input
              :disabled="!isEdit"
              type="textarea"
              row="3"
              v-model="formState.impactFraudEstimation"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="影响工期估算"
            placeholder="请输入"
            prop="impactDurationEstimation"
          >
            <el-input
              :disabled="!isEdit"
              type="textarea"
              row="3"
              v-model="formState.impactDurationEstimation"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="监理(总监)意见"
            placeholder="请输入"
            prop="supervisionOpinions"
          >
            <el-input
              :disabled="!isEdit"
              type="textarea"
              row="3"
              v-model="formState.supervisionOpinions"
            ></el-input>
          </el-form-item>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="上传文档"
                placeholder="请上传文档"
                prop="alterationAttachmentArr"
              >
                <el-upload
                  v-if="isEdit"
                  name="uploadFile"
                  multiple
                  :accept="acceptTypes"
                  :action="uploadUrl"
                  :headers="uploadHeaders"
                  :on-change="handleChange"
                  :on-remove="handleRemove"
                  :on-error="handleError"
                  :on-preview="handlePreview"
                  :file-list="defaultFileList"
                  :before-upload="beforeAvatarUpload"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持上传doc、docx、xls、xlsx、pdf、png、jpg、jpeg等格式文件,文件大小不得大于20M。
                    </div>
                  </template>
                </el-upload>
                <template v-else>
                  <el-link
                    v-for="item in formState.alterationAttachmentArr"
                    :key="item?.uuidFile"
                    icon="el-icon-folder"
                    @click.prevent="handleDownload(item)"
                  >
                    {{ item.fileName }}&emsp;
                  </el-link>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item
            label="变更类型"
            placeholder="请选择变更类型"
            prop="alterationTypeName"
          >
            <el-select
              v-model="formState.alterationTypeName"
              value-key="dicCode"
              :disabled="!isEdit"
            >
              <el-option
                class="default-option"
                v-for="item in changeTypeList"
                :label="item.dicValue"
                :key="item.dicCode"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注" placeholder="请输入" prop="remarks">
            <el-input
              :disabled="!isEdit"
              type="textarea"
              row="3"
              v-model="formState.remarks"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, computed, watch } from "vue";
import { useRouter, useRoute } from "vue-router";

import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
import { download } from "/@/utils/download";
import * as api from "/@/api/change";
import {
  postProjectTree,
  postGetContractList,
  getContractDetail
} from "/@/api/acceptance";

import {
  FileTypes
  // Rules,
  // ProjectPhaseOptions
  // DocTypeOptions
} from "../types";

const projectRef = ref<HTMLElement | null>(null) as any;
const projectTreeRef = ref<HTMLElement | null>(null) as any;
const formRef = ref<HTMLFormElement | null>(null) as any;

const router = useRouter();
const route = useRoute();

let projectList = ref([]);
let contracList = ref([]);
let changeTypeList = ref([]);

const formState = reactive({
  alterationName: "",
  projectName: null,
  projectManageId: "",
  contractName: null,
  contractId: null,
  subProjectName: "",
  segmentName: "",
  subSegmentName: "",
  alterationReason: "",
  proposedScheme: "",
  impactFraudEstimation: "",
  impactDurationEstimation: "",
  supervisionOpinions: "",
  alterationAttachmentArr: [],
  alterationTypeName: null,
  alterationTypeCode: "",
  remarks: ""
});

const Rules = {
  alterationName: [
    { required: true, message: "请输入变更名称", trigger: "blur" }
  ],
  projectName: [
    { required: true, message: "请选择所属项目", trigger: "change" }
  ],
  contractId: [{ required: true, message: "请选择合同", trigger: "change" }],
  subProjectName: [{ required: true, message: "请输入", trigger: "change" }],
  segmentName: [{ required: true, message: "请输入", trigger: "change" }],
  subSegmentName: [{ required: true, message: "请输入", trigger: "change" }],
  alterationReason: [{ required: true, message: "请输入", trigger: "change" }],
  proposedScheme: [{ required: true, message: "请输入", trigger: "change" }],
  impactFraudEstimation: [
    { required: true, message: "请输入", trigger: "change" }
  ],
  impactDurationEstimation: [
    { required: true, message: "请输入", trigger: "change" }
  ],
  supervisionOpinions: [
    { required: true, message: "请输入", trigger: "change" }
  ],
  alterationAttachmentArr: [
    { required: true, message: "请输入", trigger: "change" }
  ],
  alterationTypeName: [
    { required: true, message: "请选择变更类型", trigger: "change" }
  ]
};

const defaultProps = {
  children: "children",
  label: "projectName",
  id: "id"
};

const infoState = reactive({
  createTime: "",
  createUserName: "",
  billNum: ""
});

/* 上传 -- start */
const acceptTypes = Object.values(FileTypes).join(",");
const uploadUrl =
  import.meta.env.VITE_BASE_URL + "/snow-admin/common/file/upload";
const uploadHeaders = {
  Authorization: storageLocal.getItem("info")?.accessToken
};

let isEdit = computed(() => {
  // @ts-ignore
  if (["add", "edit"].includes(route.query.mode)) {
    return true;
  } else {
    return false;
  }
});

watch(
  () => formState.projectManageId,
  newVal => {
    if (newVal) {
      // formState.projectManageId = newVal.id;
      getContractList();
    }
  },
  {
    deep: true
  }
);

let defaultFileList = ref([]);

const handleRemove = (file, fileList) => {
  defaultFileList.value = fileList;
};

const handleChange = (file, fileList) => {
  defaultFileList.value = fileList;
  formRef.value.clearValidate();
};

const handlePreview = file => {
  console.log(file, "file");
  if (file?.response?.code !== 200 || !file?.response?.data) return;
  download(file?.response?.data);
};

const handleError = err => {
  let myError = err.toString(); //转字符串
  myError = myError.replace("Error: ", ""); // 去掉前面的" Error: "
  myError = JSON.parse(myError); //转对象
  myError?.message && NotifMessage.error(myError?.message);
  if (myError?.body?.code && [401, 403].includes(myError?.body?.code)) {
    myError?.body?.message && NotifMessage.error(myError?.body?.message);
    router.push("/login");
    storageLocal.removeItem("info");
  }
};

const handleDownload = item => {
  if (!item) return;
  download(item);
};

const onFilterFileData = (list: any[]) => {
  if (!list || !list.length) return;
  const newFileData = list.map(item => {
    // if (item.status === "success") {
    return item.response.data;
    // }
  });
  return newFileData;
};

const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return;
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

const beforeAvatarUpload = file => {
  const type = file.name.substring(file.name.lastIndexOf(".") + 1);
  if (!Object.keys(FileTypes).includes(type)) {
    NotifMessage.warning(`请上传${Object.keys(FileTypes).join("、")}等格式!`);
    return false;
  }

  const isLt2M = file.size / 1024 / 1024 < 20;

  if (!isLt2M) {
    NotifMessage.warning(`文件大小不能超过20M!`);
    return false;
  }
};
/* 上传 -- end */

const goback = () => {
  router.push("/projectsA/change/manage");
};

const getDetail = async () => {
  const params = {
    id: route.query.id
  };
  const { code, data } = await api.getChangeInfo(params);
  console.log(code, data);
  const {
    createTime,
    createUserName,
    billNum,
    alterationName,
    projectName,
    projectManageId,
    contractName,
    contractId,
    subProjectName,
    segmentName,
    subSegmentName,
    alterationReason,
    proposedScheme,
    impactFraudEstimation,
    impactDurationEstimation,
    supervisionOpinions,
    alterationAttachmentArr,
    alterationTypeName,
    alterationTypeCode,
    remarks
  } = data;

  infoState.createTime = createTime;
  infoState.createUserName = createUserName;
  infoState.billNum = billNum;

  formState.alterationName = alterationName;
  formState.projectName = projectName;
  formState.projectManageId = projectManageId;
  formState.contractName = contractName;
  formState.contractId = contractId;
  formState.subProjectName = subProjectName;
  formState.segmentName = segmentName;
  formState.subSegmentName = subSegmentName;
  formState.alterationReason = alterationReason;
  formState.proposedScheme = proposedScheme;
  formState.impactFraudEstimation = impactFraudEstimation;
  formState.impactDurationEstimation = impactDurationEstimation;
  formState.supervisionOpinions = supervisionOpinions;
  formState.alterationAttachmentArr = alterationAttachmentArr;
  formState.alterationAttachmentArr = alterationAttachmentArr;
  defaultFileList.value = onInitFileList(alterationAttachmentArr);
  formState.alterationTypeName = {
    dicValue: alterationTypeName,
    dicCode: alterationTypeCode
  };
  formState.alterationTypeCode = alterationTypeCode;
  formState.remarks = remarks;
  console.log(formState, "formState");
};

const handleSubmit = () => {
  formState.alterationAttachmentArr = onFilterFileData(defaultFileList.value);
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      const copyFormData = JSON.parse(JSON.stringify(formState));
      copyFormData.alterationTypeName = formState.alterationTypeName.dicValue;
      copyFormData.alterationTypeCode = formState.alterationTypeName.dicCode;

      console.log("onSave: ", copyFormData);
      if (route.query.mode === "add") {
        const { code, message } = await api.onAdd(copyFormData);
        console.log(code, message);
        if (code === 200) {
          NotifMessage.success("保存成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      } else {
        const { code, message } = await api.onSave(
          Object.assign(copyFormData, { id: route.query.id })
        );
        console.log(code, message);
        if (code === 200) {
          NotifMessage.success("修改成功");
          goback();
        } else {
          NotifMessage.error(message);
        }
      }
    } else {
      return false;
    }
  });
};

const handleCheckChange = () => {
  const res = projectTreeRef.value.getCurrentNode();
  formState.projectName = [res][0].projectName;
  formState.projectManageId = [res][0].id;
  formState.contractId = "";
  formState.contractName = "";
  projectRef.value.blur();
};

// 获取项目信息
const getProjectList = async () => {
  try {
    const { code, data } = await postProjectTree({});
    if (code === 200) {
      projectList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

// 获取合同信息
const getContractList = async () => {
  try {
    const params = {
      projectPathLike: formState.projectManageId
    };
    const { code, data } = await postGetContractList(params);
    if (code === 200) {
      contracList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleChangeContract = async () => {
  if (formState.contractId) {
    const params = {
      id: formState.contractId
    };
    const { code, data } = await getContractDetail(params);
    if (code === 200 && data) {
      const { projectManageId, projectName, contractName } = data;
      formState.projectName = projectName;
      formState.projectManageId = projectManageId;
      formState.contractName = contractName;
    }
  }
};

// 变更类型
const initChangeTypeList = async () => {
  try {
    const params = {
      dicType: "flow_alteration_type"
    };
    const { code, data } = await api.postDictList(params);
    changeTypeList.value = data;
    console.log(code, data);
  } catch (err) {
    console.log(err);
  }
};

initChangeTypeList();
getProjectList();

onMounted(() => {
  if (route.query.mode !== "add") {
    getDetail();
  }
});
</script>

<style lang="scss" scoped>
.content {
  :deep .el-page-header__content {
    font-size: 16px;
  }
  .card-box {
    margin-bottom: 10px;
    &--headerwrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    &--setbtn {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      width: 140px;
    }
  }

  .header__wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.width-custom220 {
  width: 220px;
}
.form-box {
  margin-top: 10px;
}
.form-info {
  margin-bottom: 20px;
}
.header-btns {
  text-align: right;
}

.el-select-dropdown__item {
  height: auto;
  // min-height: 100px;
  // max-height: 274px;
  padding: 0;
  overflow-x: hidden;
  overflow-y: hidden;
}
.el-select-dropdown_item.selected {
  font-weight: normal;
}

.el-select-dropdown_item.selected {
  font-weight: normal;
}

// .tree-option
.tree-option :deep .el-tree-node__content {
  height: auto;
  padding: 0 10px;
}
// .tree-option :deep .el-select-dropdown__list {
//   padding: 0 6px;
// }
.tree-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  margin-right: 10px;
}

.el-tree :deep .is-current .el-tree-node__label {
  color: #409eff;
  font-weight: 700;
}
.el-tree :deep .is-current .el-tree-node__children .el-tree-node__label {
  color: #606266;
  font-weight: normal;
}
.default-option :deep .el-tree-node__label {
  font-weight: normal;
  padding: 0 10px;
  // margin-right: 10px;
}

.default-option {
  padding: 0 10px;
}
</style>
